<template>
  <div style="height: auto">
    <!-- 头部搜索 -->
    <el-card style="width: 100%; margin-bottom: 10px" shadow="never">
      <el-row>
        <el-col :span="2">
          <el-input
            v-model="ordDto.number"
            style="width: 120px"
            placeholder="订单号"
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-select
            v-model="ordDto.orderType"
            placeholder="订单类型"
            style="width: 120px"
          >
            <el-option label="配送订单" value="1" />
            <el-option label="安装订单" value="2" />
          </el-select>
        </el-col>

        <el-col :span="2">
          <el-select
            v-model="ordDto.goodsaddress"
            placeholder="存放地址"
            style="width: 120px"
          >
            <el-option label="蚂蚁外仓" value="蚂蚁外仓" />
            <el-option label="成华二店" value="成华二店" />
            <el-option label="纯拉退货" value="纯拉退货" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-date-picker
            v-model="ordDto.date"
            type="date"
            placeholder="开始时间"
            default-time="yyyy-MM-dd"
            style="width: 140px; float: left"
          />
          <span
            style="
              float: left;
              line-height: 30px;
              display: block;
              text-align: center;
            "
          >
            -
          </span>
          <el-date-picker
            v-model="ordDto.end"
            type="date"
            placeholder="截止时间"
            default-time="yyyy-MM-dd"
            style="width: 140px; float: left"
          />
        </el-col>

        <el-col
          style="display: flex; justify-content: flex-end; align-items: center"
          :span="2"
        >
          <el-space :size="20">
            <el-button type="primary" size="small" @click="handleSearch"
              >搜索</el-button
            >
            <el-button type="danger" size="small">重置</el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格数据展示 EEF7FD -->
    <el-card
      style="width: 50%; background: #eef7fd; float: left"
      shadow="never"
    >
      <!-- #A2CBF8 -->
      <!-- <el-button type="primary">按区域排序</el-button>
      <el-button type="success">按体积排序</el-button>
      <el-button type="primary">按体重排序</el-button> -->
      <el-button type="danger" style="float: right"
        >共计 {{ tableData.length }} 票</el-button
      >
      <!-- @row-click="handleRowClick" -->
      <el-table
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%; margin-top: 1%"
      >
        <el-table-column label="序号" width="50" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="number"
          label="销售单号"
          width="100"
          align="center"
        ></el-table-column>

        <!-- <el-table-column
          prop="orderNumber"
          label="SAMS单号"
          width="100"
          align="center"
        ></el-table-column> -->

        <el-table-column
          prop="reservation"
          label="预约时间"
          align="center"
          width="100"
        >
          <template #default="scope">
            {{ scope.row.periodsTime }}{{ scope.row.periods ? "(" + scope.row.periods + ")" : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" align="center" Width="160"/>
        <!-- <el-table-column
          prop="area"
          label="区域"
          align="center"
          width="80"
        ></el-table-column> -->
        <el-table-column
          prop="storeBUCode"
          label="店号"
          align="center"
          width="60"
        ></el-table-column>

        <el-table-column
          prop="totalVolume"
          label="体积"
          align="center"
          width="60"
        />
        <el-table-column
          prop="totalWeight"
          label="重量"
          align="center"
          width="70"
        />
        <el-table-column
          prop="totalWeight"
          label="服务"
          align="center"
          width="240"
        >
          <template #default="scope">
            <div v-if="scope.row.serviceList">
              <label
                type="primary"
                v-for="(item, indexs) in scope.row.serviceList"
                :key="item.id"
                :style="[
                  item.isShow ? dynamicStyles : dynamicStyle,
                  dynamicStyleM,
                ]"
                @click="handleClick(scope.row, item.id, indexs)"
              >
                <span>{{ item.codetext }}</span>
                <text>{{ item.timewindowfrom }}</text>
              </label>
            </div>
            <label v-else>配送订单</label>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="85">
          <template #default="scope">
            <el-popover placement="right" :width="280" trigger="click">
              <template #reference>
                <el-button>派工</el-button>
              </template>
              <div>
                <label
                  v-for="item in disList"
                  :key="item.id"
                  style="
                    float: left;
                    color: #135294;
                    width: 120px;
                    padding: 5px;
                    border: 1px solid #a2cbf8;
                    border-radius: 5px;
                    margin-left: 2%;
                    margin-top: 2%;
                    text-align: center;
                  "
                  @click="handleConfirm(scope.row, item.id)"
                  >{{ item.dispatchingNumber }}</label
                >
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      style="
        width: 100%;
        width: 29%;
        background: #eef7fd;
        float: left;
        margin-left: 1%;
        padding-bottom: 1%;
      "
      shadow="never"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item
          v-for="(item, index) in disList"
          :key="index"
          :title="
            item.dispatchingNumber +
            ';' +
            item.poll +
            '票;' +
            item.volume +
            '方;' +
            item.weight +
            '重'
          "
          :name="index"
        >
          <el-select
            v-model="selCar"
            placeholder="选择车辆"
            style="width: 120px"
            @change="handleChangeCar(index)"
          >
            <el-option
              v-for="item in carInfo"
              :key="item.id"
              :label="item.licenseNumber"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="perVal"
            placeholder="选择驾驶员"
            multiple
            clearable
            filterable
            style="width: 300px"
            @change="handleChangePer(index)"
          >
            <el-option
              v-for="item in perList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>

          <el-table :data="item.orders" border style="width: 100%">
            <el-table-column label="序号" width="60" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="periods"
              label="时段"
              width="60"
              align="center"
            />
            <!-- <el-table-column prop="delivery" label="Date" width="100" align="center" /> -->
            <el-table-column prop="address" label="地址" />
            <el-table-column
              prop="postalCode"
              label="邮编"
              align="center"
              width="80"
            />
            <!-- <el-table-column
              prop="area"
              label="区域"
              align="center"
              width="80"
            ></el-table-column> -->
            <el-table-column
              prop="totalVolume"
              label="体积"
              align="center"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="totalWeight"
              label="重量"
              align="center"
              width="80"
            ></el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="mini"
                  link
                  @click="handleDelete(index, scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <el-button
        style="width: 100%; margin-top: 1%; float: left"
        @click="onAddItem"
        >添加派工单</el-button
      >
      <el-button
        type="primary"
        style="width: 100%; margin-top: 1%; float: left; margin-left: 0"
        @click="onSave"
        >确定</el-button
      >
    </el-card>
  </div>
</template>
  
<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import {
  findDispatchingList,
  findDispatchingSave,
  findPersonnelList,
  getCarPerList,
} from "@/api/order";

const loading = ref(false);
const tableData = ref([]);
const hostData = ref([]);

const total = ref(0);

const selectId = ref("");
const disList = ref([]);
const disnew = ref({
  id: null,
  dispatchingNumber: "",
  poll: 0,
  volume: 0,
  weight: 0,
  orders: [],
  personnels: [],
  dispatcher: "王坤",
  orderType: 1,
});

const perList = ref([]);

const tempOrder = ref({});
const tempId = ref([]);
const router = useRouter();

const selCar = ref("");
const perVal = ref([]);

const currentDate = ref("");

const carInfo = ref([]);

const ordDto = ref({
  date: "2025-06-05",
  end: "2025-06-05",
  number: "",
  ordernumber: "",
  orderType: null,
});


const carDto = ref({
  states: 0
});

const dynamicStyleM = ref({
  width: "100%",
  float: "left",
  marginTop: "1%",
  borderRadius: "5px",
  display: "flex",
  justifyContent: "space-between",
  alignItems: "center",
  flexWrap: "nowrap",
  padding: "3px",
  fontSize: "12px",
});
const dynamicStyle = ref({
  border: "1px solid #a2cbf8",
  color: "#135294",
});

const dynamicStyles = ref({
  border: "1px solid #f78989",
  color: "#f78989",
});

const perDto = ref({
  licenseNumber: "",
  states: 0,
});

onMounted(() => {
  getCarPer_List();
  getCurrentDate();
  getPerList();
  getList();
  disList.value = [
    {
      id: 1,
      dispatchingNumber: getordernumber(),
      poll: 0,
      volume: 0,
      weight: 0,
      orders: [],
      personnels: [],
      dispatcher: "王坤",
      vehicleNumber: "",
      licenseNumber: "",
      cid:null,
      orderType: 1,
      sid: [],
    },
  ];
});

//获取人车分配信息
const getCarPer_List = () => {
  getCarPerList(carDto.value).then((res) => {
    loading.value = false;
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      carInfo.value = res.data;
    }
  });
};

const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  currentDate.value = `${year}-${month}-${day}`;
  // ordDto.value.date = currentDate.value;
  // ordDto.value.end = currentDate.value;
};

const getPerList = () => {
  loading.value = true;
  findPersonnelList(perDto.value).then((res) => {
    if (res.code === 200 && res.data !== null) {
      perList.value = res.data;
    }
  });
};

const handleSearch = () => {
  getList();
};

const getList = () => {
  loading.value = true;
  findDispatchingList(ordDto.value)
    .then((res) => {
      loading.value = false;
      if (res.code === 200 && res.data !== null) {
        tableData.value = res.data;
        hostData.value = res.data;
        total.value = res.data.total;
      } else {
        loading.value = false;
        tableData.value = [];
      }
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err.message);
    });
};

const activeNames = ref(["1"]);

const handleClick = (row, id, ind) => {
  const tep = tableData.value.find((item) => item.id === row.id);
  const new_tep = tep.serviceList;
  //判断new_tep集合中是否有该id 存在删除 没有添加
  const index = new_tep.findIndex(
    (item) => item.id === id && item.isShow && item.isShow != undefined
  );
  const new_ser = new_tep[ind];

  if (index !== -1) {
    const aa = {
      ...new_ser,
      isShow: false,
    };
    new_tep[ind] = aa;
  } else {
    const aa = {
      ...new_ser,
      isShow: true,
    };
    new_tep[ind] = aa;
  }

  // tableData.value.serviceList = new_tep;
};

const handleConfirm = (row, id) => {
  selectId.value = id;
  tempOrder.value = row;

  if (row.orderType === 1) {
    const tep = disList.value.find((item) => item.id === id);
    tep.volume = (
      parseFloat(tep.volume) + parseFloat(tempOrder.value.totalVolume || 0)
    ).toFixed(2);

    tep.weight = (
      parseFloat(tep.weight) + parseFloat(tempOrder.value.totalWeight || 0)
    ).toFixed(2);
    tep.poll = tep.poll + 1;
    tep.orders.push(tempOrder.value);
  } else {
    console.log("12313");

    const temp = tableData.value.find((item) => item.id === row.id);
    const new_temp = temp.serviceList.filter((item) => item.isShow);

    if (new_temp.length == 0) {
      ElMessage.error("请选择服务项目");
      return;
    }
    const tep = disList.value.find((item) => item.id === id);
    tep.poll = tep.poll + 1;
    tep.orderType = 2;
    tep.orders.push(tempOrder.value);
    tep.id = row.id;
  }

  tempId.value.push(tempOrder.value.number);

  const filteredCollection = tableData.value.filter(
    (item) => !tempId.value.includes(item.number)
  );

  tableData.value = filteredCollection;
  selectId.value = "";
};

const handleDelete = (findex, index) => {
  // 从 disList 移除索引值为 index 的元素
  const tep = disList.value[findex].orders[index];
  disList.value[findex].poll = disList.value[findex].poll - 1;
  disList.value[findex].weight = (
    parseFloat(disList.value[findex].weight) - parseFloat(tep.totalWeight)
  ).toFixed(2);
  disList.value[findex].volume = (
    parseFloat(disList.value[findex].volume) - parseFloat(tep.totalVolume)
  ).toFixed(2);
  const teps = disList.value[findex].orders.splice(index, 1);
  console.log(teps);
  // 从 tempId数组移除指定元素
  tempId.value.splice(tempId.value.indexOf(tep.number), 1);
  const filteredCollection = hostData.value.filter(
    (item) => !tempId.value.includes(item.number)
  );
  tableData.value = filteredCollection;
};

const handleChangeCar = (index) => {
  console.log(selCar.value);
  const tep = carInfo.value.find((item) => item.id === selCar.value);

  var arr = [];
  if (tep.perList.length > 0) {
    tep.perList.forEach((item) => {
      arr.push(parseInt(item.nameId));
    });
    perVal.value = arr;
    disList.value[index].personnels = tep.perList;
  } else {
    perVal.value = [];
    disList.value[index].personnels = [];
  }
  disList.value[index].vehicleNumber = tep.vehicleNumber;
  disList.value[index].licenseNumber = tep.licenseNumber;
  disList.value[index].cid = tep.id;
  console.log(perVal.value);
};

const handleChangePer = (index) => {
  console.log(index);
  console.log(perVal.value);

  var arr = [];
  perVal.value.forEach((items) => {
    const newper = {
      nameId: "",
      name: "",
      position: "",
      tel: "",
    };
    const per_temp = perList.value.find((item) => item.id === items);
    newper.nameId = per_temp.id;
    newper.name = per_temp.name;
    newper.position = per_temp.officialPosition;
    newper.tel = per_temp.telephone;
    arr.push(newper);
  });
  disList.value[index].personnels = arr;
};

const onAddItem = () => {
  var temp = disList.value;
  disnew.value.id = disList.value.length + 1;
  disnew.value.dispatchingNumber = incrementOrderNumber(
    temp[temp.length - 1].dispatchingNumber
  );
  temp.push(disnew.value);
  disList.value = temp;
  disnew.value = {
    id: null,
    dispatchingNumber: "",
    vehicleNumber: "",
    licenseNumber: "",
    poll: 0,
    volume: 0,
    weight: 0,
    orders: [],
    personnels: [],
    orderType: 1,
    cid:null,
  };
};

const onSave = () => {
  console.log(disList.value);

  const filteredObj = Object.fromEntries(
    Object.entries(disList.value).filter(
      ([_, value]) => Array.isArray(value) && value.length > 0
    )
  );

  console.log(filteredObj);
  findDispatchingSave(disList.value).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      router.push({
        path: "/topic/dispatchingSelect",
      });
    }
  });
};

const incrementOrderNumber = (orderNumber) => {
  const prefix = orderNumber.match(/[a-zA-Z]+/)[0];
  const numberPart = parseInt(orderNumber.match(/\d+$/)[0], 10);
  const incrementedNumber = numberPart + 1;
  const paddingLength = orderNumber.match(/\d+$/)[0].length;
  const newNumberPart = incrementedNumber
    .toString()
    .padStart(paddingLength, "0");
  return prefix + newNumberPart;
};

//生成订单号
const getordernumber = () => {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  // 获取月份（注意：月份是从 0 开始计数的，所以要加 1）
  const month = currentDate.getMonth() + 1;
  // 获取日期
  const day = currentDate.getDate();
  // 创建日期对象
  return "PG" + (year % 100) + (month < 10 ? "0" + month : month) + day + "01";
};
</script>
<style scoped>
/*最外层透明*/
:deep(.el-table, .el-table__expanded-cell) {
  background-color: transparent !important;
}
/* 表格内背景颜色 */
:deep(.el-table th, .el-table tr, .el-table td) {
  background-color: transparent !important;
  border: 0;
  color: #135294;
}
/*去除底边框*/
:deep.el-table td.el-table__cell {
  border: 0;
}
:deep.el-table th.el-table__cell.is-leaf {
  border: 0;
}
/*去除底部灰条.el-table::before*/
:deep .el-table::before {
  display: none;
}
.el-pagination {
  text-align: center;
  justify-content: center;
  color: #135294;
}
:deep .el-pagination__sizes,
.el-pagination__total {
  color: #135294 !important;
}
:deep .el-pagination button {
  background-color: transparent !important;
}
:deep .el-pager li {
  background-color: transparent !important;
}
:deep(.el-pagination button.is-disabled, .el-pagination button.is-disabled) {
  background-color: transparent !important;
}
:deep .el-pagination .el-select {
  width: 100px !important;
}
</style>